import {
  S3Client,
  GetObjectCommand,
  HeadObjectCommand,
  PutObjectCommand,
} from "@aws-sdk/client-s3";

export interface S3Options {}

export class S3 {
  private client: S3Client;
  private bucket: string = "d3-engine";

  constructor(options: any) {
    this.client = new S3Client(options);
  }

  setBucket(v: string) {
    this.bucket = v;
  }

  // 上传文件
  uploadFile(
    filePath: string,
    file: ArrayBuffer | Blob,
    forceCheck = true
  ): Promise<boolean> {
    const putCommand = new PutObjectCommand({
      Bucket: this.bucket,
      Key: filePath,
      Body: file,
    });
    const executeCmd = () => {
      return this.client
        .send(putCommand)
        .then(() => {
          return Promise.resolve(true);
        })
        .catch(() => {
          return Promise.resolve(false);
        });
    };
    if (forceCheck) {
      return this.checkIfExist(filePath).then((exist: boolean) => {
        if (exist) {
          return Promise.resolve(true);
        } else {
          // * 文件不存在，上传文件
          return executeCmd();
        }
      });
    } else {
      return executeCmd();
    }
  }

  // 检查文件是否已经存在
  checkIfExist(key: string): Promise<boolean> {
    const headCommand = new HeadObjectCommand({
      Bucket: this.bucket,
      Key: key,
    });
    return this.client
      .send(headCommand)
      .then(() => {
        return Promise.resolve(true);
      })
      .catch(() => {
        return Promise.resolve(false);
      });
  }

  /**
   * @description 下载文件
   * @param key 文件路径
   */
  downloadFile(key: string): Promise<any> {
    const getCommand = new GetObjectCommand({
      Bucket: this.bucket,
      Key: key,
    });
    return this.client
      .send(getCommand)
      .then((res: any) => {
        return Promise.resolve(res.Body);
      })
      .catch(() => {
        console.error(`${key}:downloadFile error`);
      });
  }
}
